import React, { useEffect, useState } from "react";
import { Swiper, SwiperItem, View, Image, Input, Text, Textarea, Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import Comments from "../comments";
import { articleType, commentType } from "@/types";
import { TimeFormart } from "@/utils/format";
import http from "@/request";
import { HideLoading, ShowLoading, ShowToast } from "@/utils";
import Response from "./response"
import { eventBus } from '@/event-bus';

const ArticlePreview: React.FC<{
    article: articleType,
    isPreview?: boolean,
    onBack?: () => void
}> = ({ article, isPreview, onBack }) => {
    const [currentIndex, setCurrentIndex] = useState<number>(0)
    const [commentList, setCommentList] = useState<commentType[]>([])
    const [responseShow, setResponseShow] = useState(false)
    const [comment, setComment] = useState<commentType>()
    const [isLiked, setIsLiked] = useState<number>()

    const previewImg = (index, urls) => {
        Taro.previewImage({
            urls,
            current: index
        });
    }

    const onDeleteComment = (comment: commentType) => {
        setCommentList(commentList.map(item => {
            if (item.id === comment.id) {
                item.isDeleted = 1
                item.content = '已删除'
            }
            return item
        }))
    }

    // TODO 加载更多的逻辑还没做 删除也没做
    const queryCommentList = () => {
        if (!article.id) return
        ShowLoading()
        http.post('/article-comment/page', {
            page: 1,
            size: 99,
            id: article.id
        }).then(res => {
            HideLoading()
            setCommentList(res.data.records || [])
        }).catch(err => {
            ShowToast(err.msg || '获取评论失败')
        })
    }
    const saveComment = (content) => {
        ShowLoading('正在发布')
        // 发布一级评论
        const params: commentType = {
            articleId: article.id,
            content
        }
        // 回复一级评论
        if (comment) {
            params.parentId = comment.id
            if (comment.parentId) {
                // 回复二级评论
                params.toUserName = comment.userName
            }
        }
        http.post('/article-comment/addOrUpdate', params).then(_ => {
            setResponseShow(false)
            HideLoading()
            queryCommentList()
        }).catch(err => {
            ShowToast(err.msg || '评论发表失败')
        })
    }
    const onResponse = (res?: commentType) => {
        setResponseShow(true)
        setComment(res)
        // 更新文章列表
        console.log('更新文章列表');
        eventBus.emit('refreshArticleList');
    }

    const doLike = () => {
        const val = article.isLiked === 1 ? 0 : 1
        ShowLoading()
        http.put(`/article/dolike/${article.id}?likeType=${val}`).then(_ => {
            ShowToast('操作成功')
            setIsLiked(val)
            article.isLiked = val
            // 更新文章列表
            eventBus.emit('refreshArticleList');
        }).catch(err => {
            ShowToast(err.msg || '操作失败')
        })
    }

    useEffect(() => {
        queryCommentList()
        setIsLiked(article.isLiked)
    }, [article])

    Taro.useShareAppMessage(_ => {
        return {
            title: `${article?.title}`,
            path: `/pages/article/detail/index?id=${article?.id}&sharetime=${new Date().getTime()}`
        }
    })

    return (
        <View className="article-preview-component flex-column">
            {
                article.imgs?.length ?
                    <Swiper
                        className='swiper-container'
                        indicatorColor='#999'
                        indicatorActiveColor='#333'
                        indicatorDots
                        current={currentIndex}
                        onChange={e => setCurrentIndex(e.detail.current)}
                        adjustHeight="highest">
                        {
                            article.imgs?.map((url, index) => {
                                return <SwiperItem>
                                    <View className="article-img-container flex-column flex-center"
                                        onClick={() => previewImg(index, article.imgs)}>
                                        <Image className="article-img"
                                            mode="widthFix"
                                            src={url}
                                            key={index}>
                                        </Image>
                                    </View>
                                </SwiperItem>
                            })
                        }
                    </Swiper> : null
            }
            <View className="title font-size32">{article.title}</View>
            {
                (article.content || '').split('\n').map((text, index) => {
                    return (
                        <View className="content font-size28" key={index}>{text}</View>
                    )
                })
            }
            <View className="time-formart font-size24">{TimeFormart(article.editTime)}</View>
            {
                !isPreview ? commentList.map(item => {
                    return <Comments onResponse={onResponse} onDelete={onDeleteComment} comment={item} key={item.id}></Comments>
                }) : null
            }
            <View className="page-bottom flex-column flex-item card-background">
                <View className="half-line"></View>
                <View className="comment-input-container flex-row flex-item">
                    {
                        isPreview ?
                            <>
                                <View className="flex1"></View>
                                <View onClick={onBack} className="btn save-btn flex-row flex-center">
                                    <Text className="data-val font-size24">返回</Text>
                                </View>
                                <View className="flex1"></View>
                            </> :
                            <>
                                <View className="comment-input flex1" onClick={() => onResponse(undefined)}>说点什么...</View>
                                <View onClick={doLike} className="data-item flex-row flex-item">
                                    {
                                        isLiked === 1 ?
                                            <Text className="data-icon font-size40 iconfont icon-dianzan-full"></Text> :
                                            <Text className="data-icon font-size40 iconfont icon-dianzan"></Text>
                                    }
                                    <Text className="data-val">{article.likeNum}</Text>
                                </View>
                                <View className="data-item flex-row flex-item">
                                    <Text className="data-icon font-size40 iconfont icon-a-44tubiao-132"></Text>
                                    <Text className="data-val font-size28">分享</Text>
                                    <Button className="share-btn" openType="share"></Button>
                                </View>
                            </>
                    }
                </View>
            </View>
            <Response show={responseShow} onFinish={saveComment} onClose={() => setResponseShow(false)}></Response>
        </View>
    )
}

export default ArticlePreview